package com.grape.dsaa.lineartable.stack.core;

import com.grape.dsaa.lineartable.stack.Stack;

import java.util.EmptyStackException;

/**
 * 描述:自定义链表实现栈
 * @author: myx
 * @date: 2019-04-28
 * Copyright © 2019-grape. All rights reserved.
 */
public class MyLinkedStack<E> implements Stack<E> {
	
	private static class Node<E> {
		public E data; //数据域
		public Node<E> next; //指针域
		
		public Node(E val, Node<E> next) {
			this.data = val;
			this.next = next;
		}
	}

	//栈顶指针
	private Node<E> top;

	//栈中元素数量
	private int size;
	
	public MyLinkedStack() {
		System.out.println();
		top = null;
		size = 0;
	}

	@Override
	public boolean empty() {
 		return size == 0;
	}

	@Override
	public int size() {
 		return size;
	}

	@Override
	public void push(E item) {
		top = new Node<E>(item, top);
		size++;
		
	}

	@Override
	public E pop() {
		if(size == 0) {
			throw new EmptyStackException();
		}
		E result = top.data;
		top = top.next;
		return result;
	}

	@Override
	public E peek() {
		if(size == 0) {
			throw new EmptyStackException();
		}
		
		return top.data;
	}
}
